var functionOpen = false;
chrome.storage.sync.get("linkOpen", ({ linkOpen }) => {
    functionOpen = linkOpen;

});

$(function () {

    if(functionOpen){
        console.log("邮件过滤功能打开");
    }else{
        console.log("邮件过滤功能关闭");
        return;
    }

    if(!checkPage())
        return;

    let email_list_wrapper = get_163_EmailsList();
    // console.log(email_list);
    let email_list = [];
    for (let i = 0; i < email_list_wrapper.length; i++) {
        let node = email_list_wrapper.eq(i);
        if(node.attr('sign')!=='letter')
            continue;
        email_list.push(
            email_list_wrapper.eq(i).find('.da0').html()
        ); //将节点信息转换成元组
    }
    // console.log(email_list);

    let emails_json = {
        emails: JSON.stringify(email_list)
    };
    // console.log(emails_json);

    console.log("正在对邮箱："+$('#spnUid').html()+" 中的邮件进行垃圾邮件过滤");
    let mailbox_address = $('#spnUid').html();
    $.ajax({
        xhrFields: {
            withCredentials: true   //解决跨域问题
        },
        url: "http://127.0.0.1:5000/mark_email",
        type: "POST",
        // data: {
        //     "emails":emails,
        //     "mailbox_address": mailbox_address
        // },
        data: emails_json,
        dataType: "json",
        // contentType: "multipart/form-data",
        // processData: false,
        success: function (data){
            // console.log(data);
            if(data['msg']==="数据已处理")
                rendering_mark(data['result']);
        },
        error: function (err){
            alert(err.statusText + "访问错误！查看是否开启后台");
        }
    });
    // alert("访问后台结束");
});


// 查询当前邮箱页面是否符合标准（比如是否正在查看邮件）
function checkPage() {
    let navTree = $('#dvNavTree');
    let mail_component = navTree.children(0).children(0).children(0);
    let flag = mail_component.attr('aria-checked');
    return flag === true || flag === "true";
}

function get_163_EmailsList(){
    let emailContainer = $('#dvContainer');
    let emailListWrapper = emailContainer.children(0).children('.frame-main-cont-body')
        .children(0).children(0).children('.tv0');
    // console.log(emailListWrapper.html());
    return emailListWrapper.children();
}

//将已获得的垃圾邮件标签绘制到页面上
function rendering_mark(data) {
    // console.log(data);
    let email_list_wrapper = get_163_EmailsList();
    for (let i = 0; i < email_list_wrapper.length; i++) {
        let node = email_list_wrapper.eq(i);
        let content = node.find('.da0').html();
        if(node.attr('sign')!=='letter')
            continue;
        let hV0 = node.find('.hV0'); //这是163邮箱原来放置邮件标签的地方
        if(data[content]===1 || data[content]==="1")
            hV0.append("<img src='https://img.shields.io/badge/-%E5%9E%83%E5%9C%BE%E9%82%AE%E4%BB%B6-orange' />")
    }
}

